<?php

/**
 * Created by PhpStorm.
 * User: dumbledore
 * Date: 2017/12/25
 * Time: 上午10:12
 */
class Order extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->model('user_model');
        $this->load->model('courier_model');
        $this->load->model('box_model');
        $this->load->model('order_model');
        $this->load->library('form_validation'); //加载表单验证类库
        $this->load->helper('json');
        $this->load->helper('common');
        $this->output->set_content_type('application/html;charset=utf-8');
    }

    // 创建订单
    public function create()
    {
        $post = $this->input->post();
        if ($post['user_id'] && $post['box_id']) {
            // 箱子状态
            $box_info = $this->box_model->query_box_info($post['box_id']);
            if (!$box_info) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "出错啦，没有这个箱子，请联系供应商"));
            }
            if ($box_info['use_status'] != 1 && $box_info['use_status'] != 2) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "出错啦，这个箱子正在使用中或者已经被禁用"));
            }
            // 箱子要锁住的
            $re = $this->box_model->query_box_lock_status($post['box_id']);
            if ($re != 'close') {
                send_json(array('code' => -1, 'data' => '', 'msg' => "请耐心等待箱子锁上"));
            }
            $order_bn               = trade_no();
            $data_arr['order_bn']   = $order_bn;
            $data_arr['box_id']     = $post['box_id'];
            $data_arr['status']     = 1;
            $data_arr['user_id']    = $post['user_id'];
            $data_arr['start_time'] = date("Y-m-d H:i:s");
            $data_arr['password']   = '';
            $this->db->insert("app_order", $data_arr);
            $insert_id = $this->db->insert_id();
            if ($insert_id) {
                // 如果是快递员送来的 算作结束
                //                $this->db->where(array("box_id"=>$post['box_id'],"status"=>1))->update('app_courier_box',array("status"=>0));
                //                $this->courier_model->update_app_courier_box('0',$post['box_id'],$post['uid']);

                // 修改箱子状态
                $this->db->where(array("id" => $post['box_id']))->update('app_box', array("use_status" => 3));
                send_json(array('code' => 0, 'data' => array('order_id' => $insert_id, 'order_bn' => $order_bn), 'msg' => "创建成功"));
            }
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
    }

    // 设置接受方(从收件人列表中选择)
    public function add_receiver()
    {
        $post = $this->input->post();
        if ($post['choose_uid'] && $post['order_id'] && $post['uid']) {
            $choose_user_info = $this->user_model->query_wechat_info_by_id($post['choose_uid']);
            if (!$choose_user_info) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "没有该用户"));
            }
            $box_id      = $this->db->query("select box_id from app_order WHERE id = " . $post['order_id'])->row_array()['box_id'];
            $lock1_state = $this->box_model->query_box_lock_status($box_id);
            if ($lock1_state != 'close') {
                send_json(array('code' => -1, 'data' => '', 'msg' => "请先锁箱子"));
            }
            $bool = $this->db->where(array("id" => $post['order_id']))->update('app_order', array("receiver_user_id" => $post['choose_uid']));
            if ($bool) {
                // 存入我的寄件人列表
                $this->user_model->add_app_user_receiver($post['uid'], $post['choose_uid']);
                send_json(array('code' => 0, 'data' => '', 'msg' => "设置成功"));
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => "设置失败"));
            }
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
    }

    // 设置接受方(分享时候)
    public function add_receiver_by_share()
    {
        $post = $this->input->post();
        if ($post['uid'] && $post['order_id']) {
            $choose_user_info = $this->user_model->query_wechat_info_by_id($post['uid']);
            if (!$choose_user_info) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "没有该用户"));
            }
            // 订单信息
            $order_info = $this->order_model->query_order_info($post['order_id']);
            if (!$order_info) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "没有此订单"));
            }
            if ($order_info['status'] != 1) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "订单状态错误"));
            }
            $box_id      = $order_info['box_id'];
            $lock1_state = $this->box_model->query_box_lock_status($box_id);
            if ($lock1_state != 'close') {
                send_json(array('code' => -1, 'data' => '', 'msg' => "请先锁箱子"));
            }

            $bool = $this->db->where(array("id" => $post['order_id']))->update('app_order', array("receiver_user_id" => $post['uid']));
            if ($bool) {
                // 存入我的寄件人列表
                $this->user_model->add_app_user_receiver($order_info['user_id'], $post['uid']);
                send_json(array('code' => 0, 'data' => '', 'msg' => "设置成功"));
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => "设置失败"));
            }
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
    }

    // 取消订单
    public function cancel_order()
    {
        $post = $this->input->post();
        if ($post['order_id'] && $post['user_id']) {
            // 订单详情
            $box_info = $this->order_model->query_order_info($post['order_id']);
            if (!$box_info) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "取消失败，没有该订单"));
            }
            $box_id = $box_info['box_id'];
            $query  = $this->db->query("select user_id from app_order WHERE id = " . $post['order_id']);
            $info   = $query->row_array();
            if (!$info || $info['user_id'] != $post['user_id']) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "取消失败，用户信息不匹配"));
            }
            $bool = $this->db->where(array("id" => $post['order_id']))->update('app_order', array("status" => 0));
            if ($bool) {
                // 修改箱子状态
                $this->db->where(array("id" => $box_id))->update('app_box', array("use_status" => 1));
                send_json(array('code' => 0, 'data' => '', 'msg' => "取消成功"));
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => "取消失败"));
            }
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }

    }

    // 查询客户进行中的订单的数量
    public function query_going_order_count()
    {
        if (isset($_GET['uid']) && $_GET['uid']) {
            $count = $this->order_model->count_going_orders($_GET['uid']);
            send_json(array('code' => 0, 'data' => array('count' => $count), 'msg' => "success"));

        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
    }

    // 订单列表查询
    public function query_order_list()
    {
        if ($_GET['id']) {
            $user_id = $_GET['id'];
            $type    = isset($_GET['type']) ? $_GET['type'] : '1';
            if ($type == 1) {
                $order_status = [1, 2];
                $type         = 1;
            } else {
                $order_status = [0, 2];
                $type         = 2;
            }
            $page  = isset($_GET['page']) ? (int) $_GET['page'] : 1;
            $psize = isset($_GET['psize']) ? (int) $_GET['psize'] : 10;
            // 作为收货人
            $order_list = $this->order_model->query_sending_order($order_status, $user_id, $user_id, '', $page, $psize, $type);
            foreach ($order_list as &$order_info) {
                // 物流信息
                if ($order_info['tracking_number']) {
                    $tracking_info               = $this->order_model->order_logistics($order_info['tracking_number']);
                    $order_info['tracking_info'] = $tracking_info;
                }
            }
            send_json(array('code' => 0, 'data' => array('order_list' => $order_list), 'msg' => "请求成功"));
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }

    }

    // 计算价格（支付前结算价格）
    public function deal_money()
    {
        $post = $this->input->post();
        if ($post['order_id'] && $post['user_id']) {
            $order_info = $this->order_model->query_order_info($post['order_id']);
            if ($order_info['user_id'] != $post['user_id'] && $post['user_id'] != $order_info['receiver_user_id']) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "你没有权限获取订单信息"));
            }
            if ($order_info['status'] != 2) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "请先结束订单"));
            }
            $box_id  = $order_info['box_id'];
            $sql     = "select a.price from app_box_type a LEFT JOIN app_box b ON a.id = b.type_id WHERE b.id = " . $box_id;
            $keyinfo = $this->db->query($sql)->row_array();
            if (!$keyinfo) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "每日费用未设置"));
            }
            $rate  = $keyinfo['price'];
            $days  = diffBetweenTwoDays($order_info['end_time'], $order_info['start_time']);
            $money = $order_info['fee'];
//            $this->db->where(array("id"=>$post['order_id']))->update('app_order',array("fee"=>$money));
            send_json(array('code' => 0, 'data' => array('days' => $days, 'rate' => $rate, 'money' => $money), 'msg' => "success"));
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
    }

    // 结束订单
    public function end_order()
    {
        $post = $this->input->post();
        if ($post['order_id'] && $post['user_id']) {

            // 箱子位置信息
            $order_info    = $this->order_model->query_order_info($post['order_id']);
            $box_bn        = $this->box_model->query_box_info($order_info['box_id'])['box_bn'];
            $box_info      = $this->box_model->query_box_detail($box_bn);
            $box_latitude  = $box_info['latitude'];
            $box_longitude = $box_info['longitude'];

            // 校验位置信息
            $stake_list        = $this->box_model->query_stake_list();
            $distance_standard = 100;
            $flag              = 0;
            $stake_info        = '';
            foreach ($stake_list as $sl) {
                // 纬度
                $latitude = $sl['latitude'];
                // 经度
                $longitude = $sl['longitude'];
                $distance  = distanceBetween($latitude, $longitude, $box_latitude, $box_longitude);
                if ($distance < $distance_standard) {
                    $flag       = 1;
                    $stake_info = $sl;
                    break;
                }
            }
            if (!$flag) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "未将智能箱还至固定桩，无法结束订单"));
            }

            // 修改订单状态
            $wechat_id = $this->user_model->query_wechat_info_by_id($post['user_id'])['wechat_id'];
            if (!$wechat_id) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "没有该用户"));
            }
            if ($order_info['user_id'] != $post['user_id'] && $post['user_id'] != $order_info['receiver_user_id']) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "你没有权限关闭改订单"));
            }
            if ($order_info['status'] == 1) {
                // 箱子状态
                $box_id = $order_info['box_id'];

                //开启事务
                $this->db->trans_begin();
                $res  = $this->db->where(array("id" => $box_id))->update('app_box', array("use_status" => 1, 'stake_id' => $stake_info['id']));
                $res2 = $this->db->where(array("id" => $post['order_id']))->update('app_order', array("status" => 2, "end_time" => date("Y-m-d H:i:s")));
                // 如果是快递员送来的 算作结束
                //                $this->db->where(array("box_id"=>$box_id,"status"=>1))->update('app_courier_box',array("status"=>0));
                $b_info = $this->courier_model->query_box_status($box_id);
                if ($b_info) {
                    $this->courier_model->update_app_courier_box('0', $box_id, $b_info['courier_id']);
                }
                // 计算价格
                $res3 = $this->order_model->deal_order_money($box_id, $post['order_id']);

                if ($res && $res2 && $res3) {
                    $this->db->trans_commit();
                    // 返回订单的详情
                    $order_info = $this->order_model->query_order_info($post['order_id']);
                    $box_info   = $this->box_model->query_box_info($order_info['box_id']);
                    send_json(array('code' => 0, 'data' => array('order_info' => $order_info, 'box_info' => $box_info), 'msg' => "订单已结束"));
                } else {
                    $this->db->trans_rollback();
                    send_json(array('code' => 0, 'data' => '', 'msg' => "结束订单失败"));
                }

            } else {
                if ($order_info['status'] == 0) {
                    send_json(array('code' => -1, 'data' => '', 'msg' => "订单已取消，无法结束订单"));
                } else if ($order_info['status'] == 2) {
                    send_json(array('code' => -1, 'data' => '', 'msg' => "订单已结束"));
                }

            }
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
    }

    // 历史订单详情
    public function order_detail()
    {
        if (isset($_GET['order_id']) && isset($_GET['user_id']) && $_GET['order_id'] && $_GET['user_id']) {
            $order_info = $this->order_model->query_order_info($_GET['order_id']);
            // 箱子信息
            $box_info  = $this->box_model->query_box_info($order_info['box_id']);
            $wechat_id = $this->user_model->query_wechat_info_by_id($_GET['user_id'])['wechat_id'];
            if (!$wechat_id) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "没有该用户"));
            }
            if ($order_info['user_id'] != $_GET['user_id'] && $_GET['user_id'] != $order_info['receiver_user_id']) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "你没有权限查看订单"));
            }
//            if($order_info['status'] != 2)
            //            {
            //                send_json(array('code'=>-1,'data'=>'','msg'=>"订单尚未结束"));
            //            }

            // 快递员信息信息
            $courier_info = '';
            if ($order_info['courier_id']) {
                $courier_info = $this->courier_model->query_courier_info($order_info['courier_id']);
            }

            // 物流信息
            $tracking_info = '';
            if ($order_info['tracking_number']) {
                $tracking_info = $this->order_model->order_logistics($order_info['tracking_number']);
            }
            send_json(array('code' => 0, 'data' => array('order_detail' => $order_info, 'box_info' => $box_info, 'courier_info' => $courier_info, 'tracking_info' => $tracking_info), 'msg' => "success"));

        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
    }

    // 进行中订单详情
    public function going_order_detail()
    {
        if (isset($_GET['order_id']) && isset($_GET['user_id']) && $_GET['order_id'] && $_GET['user_id']) {
            $order_info = $this->order_model->query_order_info($_GET['order_id']);
            $wechat_id  = $this->user_model->query_wechat_info_by_id($_GET['user_id'])['wechat_id'];
            if (!$wechat_id) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "没有该用户"));
            }
            if ($order_info['user_id'] != $_GET['user_id'] && $_GET['user_id'] != $order_info['receiver_user_id']) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "你没有权限查看订单"));
            }
            if ($order_info['status'] == 0) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "订单已取消"));
            }

            // 快递员信息信息
            $courier_info = '';
            if ($order_info['courier_id']) {
                $courier_info = $this->courier_model->query_courier_info($order_info['courier_id']);
            }

            // 物流信息
            $tracking_info = '';
            if ($order_info['tracking_number']) {
                $tracking_info = $this->order_model->order_logistics($order_info['tracking_number']);
            }

            // 要改实时的
            $box_info = $this->box_model->query_box_info($order_info['box_id']);
            // 箱子信息 实时的信息
            //$box_real_time_detail = $this->box_model->query_box_detail($box_info['box_bn']);
            $box_real_time_detail = "";
            send_json(array('code' => 0, 'data' => array('order_detail' => $order_info, 'courier_info' => $courier_info, 'box_real_time_detail' => $box_real_time_detail, 'tracking_info' => $tracking_info, 'box_info' => $box_info), 'msg' => "success"));

        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
    }

    //数据监控
    public function data_monitor()
    {
        $post          = $this->input->post();
        $stime         = strtotime(date('Y-m-d', $post['time']));
        $etime         = $stime + 23 * 60 * 60;
        $box_id        = $post['box_id'];
        $interval      = $post['interval'];
        $interval_type = $post['interval_type'];
        $data_type     = $post['data_type'];

        $url = $this->config->item("suda_base_url") . "FrameMessage.aspx?id=" . $box_id . "&start=" . $stime . "&end=" . $etime . "&int=" . $interval . "&inttype=" . $interval_type . "&type=" . $data_type . "";

        //发送数据
        $get_data = curl_request($url);
        if ($get_data) {
            $return_info = json_decode($get_data, true);
            $res         = array();
            if ($return_info['state']['code'] == 0) {
                $res['data'] = $return_info['data'];
                send_json(array('code' => 0, 'data' => $res, 'msg' => "success"));
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => "failure"));
            }
        }
    }
}
